package com.pumpkin.server.controller;

import com.pumpkin.server.commons.ResBean;
import com.pumpkin.server.components.AdminLoginParam;
import com.pumpkin.server.pojo.Admin;
import com.pumpkin.server.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 处理用户登录
 */

@Api(tags = "LoginController")
@RestController
public class LoginController {

    @Autowired
    private IAdminService adminService;

    /**
     * 登录请求
     * @param adminLoginParam
     * @param request
     * @return
     */
    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public ResBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request) {
        return adminService.login(adminLoginParam.getUsername(),adminLoginParam.getPassword(),adminLoginParam.getCode(),request);
    }

    /**
     * 获取当前登录的用户信息
     * @param principal
     * @return
     */
    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal) {
        if (null == principal) {
            return null;
        }
        String username = principal.getName();
        Admin admin = adminService.getAdminByUserName(username);
        //不给前端返回敏感信息（密码）
        admin.setPassword(null);
        //给用户设置角色列表
        admin.setRoles(adminService.getRoles(admin.getId()));
        return admin;
    }

    /**
     * 退出请求
     * @return
     */
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public ResBean logout() {
        return ResBean.success("注销成功！");
    }
}
